package com.zhangtai.modules.controller.admin;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.common.annotation.SysAuthorityLog;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.ImgUrlDao;
import com.zhangtai.modules.dao.ShiftDao;
//import com.zhangtai.modules.dao.ssqlDao.JobDaoMssql;
import com.zhangtai.modules.dto.DistributeLeaveDto;
import com.zhangtai.modules.dto.FrequencyDto;
import com.zhangtai.modules.dto.LeaveInfoDto;
import com.zhangtai.modules.entity.common.ImgUrlEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.leave.DistributeLeaveEntity;
import com.zhangtai.modules.entity.leave.ShiftEntity;
import com.zhangtai.modules.entity.system.UserEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.common.ImgUrlService;
import com.zhangtai.modules.service.employee.EmployeeInfoService;
import com.zhangtai.modules.service.leave.DistributeLeaveService;
import com.zhangtai.modules.service.leave.LeaveInfoService;
import com.zhangtai.modules.service.leave.ShiftService;
import com.zhangtai.modules.service.system.UserService;
import com.zhangtai.modules.vo.DistributeLeaveVo;
import com.zhangtai.modules.vo.LeaveListVo;
import com.zhangtai.modules.vo.ShiftVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import io.netty.util.internal.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("leave")
@RestController
@Slf4j
@Api(tags = "请假调休调班")
public class LeaveController {

    @Autowired
    private LoginController loginController;
    @Autowired
    private BaseMssqlServiceImpl baseMssqlService;
    @Autowired
    private LeaveInfoService leaveInfoService;
//    @Autowired
//    private JobDaoMssql jobDaoMssql;
    @Autowired
    private JobController jobController;
    @Autowired
    private DistributeLeaveService distributeLeaveService;
    @Autowired
    private ShiftService shiftService;
    @Autowired
    private ShiftDao shiftDao;
    @Autowired
    private ImgUrlService imgUrlService;
    @Autowired
    private ImgUrlDao imgUrlDao;
    @Autowired
    private EmployeeInfoService employeeInfoService;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private UserService userService;

    @PostMapping("/getLeaveList")
    @ApiOperation(value="查找请假调休列表")
    @PreAuthorize("hasAuthority('emp:qjtx:get')")
    public R<PageResult<LeaveInfoDto>> getLeaveList(HttpServletRequest request, @RequestBody @Valid LeaveListVo vo)throws Exception{
        List<Long> jobIds = null;
        List<Long>  unitIds = null;
        List<Long> orgId = null;
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        //公司
        if(!StringUtil.isNullOrEmpty(vo.getOrgName())){
//            orgId = jobDaoMssql.findOrgByName(vo.getOrgName());
        }
        //职位
        if(!StringUtil.isNullOrEmpty(vo.getJobName())){
            jobIds = baseMssqlService.findJobIdByJobName(vo.getJobName());
        }
        if(!StringUtil.isNullOrEmpty(vo.getUnitName())){
//            unitIds = jobDaoMssql.findOrgByName(vo.getUnitName());
        }
        List<Long> orgIds = (List<Long>) checkR.getData();

        PageResult<LeaveInfoDto> list = leaveInfoService.getLeaveListSystem(orgIds,unitIds,jobIds,orgId,vo.getType(),vo.getName(),vo.getPageNum(),vo.getPageSize());
        List<LeaveInfoDto> leaveInfo  = list.getList();
        for(LeaveInfoDto info:leaveInfo){
            info.setUnitname(jobController.orgMap.get(info.getUnitId()));
            info.setJobname(jobController.jobMap.get(info.getJobId()));
        }
        return R.ok(list);
    }

    @PostMapping("/getDistributeLeaveList")
    @ApiOperation(value="查找零星调休列表")
    @PreAuthorize("hasAuthority('emp:qjtx:get')")
    public R<PageResult<DistributeLeaveDto>> getDistributeLeaveList(@RequestBody @Valid DistributeLeaveVo vo, HttpServletRequest request)throws Exception{
        List<Long>  unitIds = null;
        List<Long> orgId = null;
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        //公司
        if(!StringUtil.isNullOrEmpty(vo.getOrgName())){
//            orgId = jobDaoMssql.findOrgByName(vo.getOrgName());
        }
        if(!StringUtil.isNullOrEmpty(vo.getUnitName())){
//            unitIds = jobDaoMssql.findOrgByName(vo.getUnitName());
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult<DistributeLeaveEntity> result = distributeLeaveService.getLeaveList(null,orgIds,orgId,unitIds,vo.getPageNum(),vo.getPageSize());
        List<DistributeLeaveEntity> list = result.getList();
        List<DistributeLeaveDto> dtoList = new ArrayList<>();
        for (DistributeLeaveEntity entity:list){
            DistributeLeaveDto dto = BeanUtilsMabach.doToDto(entity,DistributeLeaveDto.class);
            dto.setJobname(jobController.jobMap.get(dto.getJobId()));
            dto.setOrgname(jobController.orgMap.get(dto.getOrgId()));
            dto.setUnitname(jobController.orgMap.get(dto.getUnitId()));
            dtoList.add(dto);
        }
        PageResult<DistributeLeaveDto> dtoResult = new PageResult<>();
        dtoResult.setList(dtoList);
        dtoResult.setCurrPage(result.getCurrPage());
        dtoResult.setPageSize(result.getPageSize());
        dtoResult.setTotalCount(result.getTotalCount());
        dtoResult.setTotalPage(result.getTotalPage());
        return R.ok(dtoResult);
    }



    @GetMapping("/getShiftList")
    @ApiOperation(value="分页查询调班列表")
    public R getShiftList(@RequestParam(value = "shiftName", required = false) String shiftName,
                          @RequestParam(value = "shiftOrgName", required = false) String shiftOrgName,
                          @RequestParam(value = "shiftUnitName", required = false) String shiftUnitName,
                          @RequestParam(value = "shiftJobName", required = false) String shiftJobName,
                          @RequestParam(value = "shiftDateStart", required = false) String shiftDateStart,
                          @RequestParam(value = "shiftDateEnd", required = false) String shiftDateEnd,
                          @RequestParam(value = "frequency", required = false) List<Integer> frequency,
                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          HttpServletRequest request) throws Exception {
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }
        List<Long> orgIds = (List<Long>) checkR.getData();
        PageResult result=  shiftService.queryPage(shiftName,null,orgIds,shiftOrgName,shiftUnitName,shiftJobName,shiftDateStart,shiftDateEnd,frequency,pageNum,pageSize);
        return R.ok(result);
    }

    @GetMapping("/getShiftFrequency")
    @ApiOperation(value="根据调班时间查询调班班次")
    public R getShiftFrequency(@RequestParam(value = "shiftDate") String shiftDate,
                               @RequestParam(value = "shiftOid") String shiftOid,
                               @RequestParam(value = "beShiftOid") String beShiftOid,
                               HttpServletRequest request) throws Exception {
        JSONObject data = loginController.getUserInfo(request).getData();
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }
        //暂时自定义
        //后面去东软取
        JSONObject object=new JSONObject();
        FrequencyDto frequencyDto1=new FrequencyDto();
        frequencyDto1.setId("1");
        frequencyDto1.setName("早班");

        FrequencyDto frequencyDto2=new FrequencyDto();
        frequencyDto2.setId("2");
        frequencyDto2.setName("中班");

        FrequencyDto frequencyDto3=new FrequencyDto();
        frequencyDto3.setId("3");
        frequencyDto3.setName("晚班");

        List<FrequencyDto> frequencyList=new ArrayList<>();
        frequencyList.add(frequencyDto1);
        frequencyList.add(frequencyDto2);
        frequencyList.add(frequencyDto3);
        object.put("frequencyList",frequencyList);
        List<FrequencyDto> beFrequencyList=new ArrayList<>();
        beFrequencyList.add(frequencyDto1);
        beFrequencyList.add(frequencyDto2);
        beFrequencyList.add(frequencyDto3);
        object.put("beFrequencyList",beFrequencyList);
        return R.ok(object);
    }

    @GetMapping("/getFrequencyList")
    @ApiOperation(value="查询调班班次列表")
    public R getShiftFrequency() throws Exception {
        //暂时自定义
        //后面去东软取
        List<FrequencyDto> frequencyDtoList=new ArrayList<>();

        FrequencyDto frequencyDto1=new FrequencyDto();
        frequencyDto1.setId("1");
        frequencyDto1.setName("早班");
        frequencyDtoList.add(frequencyDto1);

        FrequencyDto frequencyDto2=new FrequencyDto();
        frequencyDto2.setId("2");
        frequencyDto2.setName("中班");
        frequencyDtoList.add(frequencyDto2);

        FrequencyDto frequencyDto3=new FrequencyDto();
        frequencyDto3.setId("3");
        frequencyDto3.setName("晚班");
        frequencyDtoList.add(frequencyDto3);
        return R.ok(frequencyDtoList);
    }

    @PostMapping("/saveAndUpdateShiftInfo")
    @ApiOperation(value="保存或修改调班信息")
    @SysAuthorityLog(value="保存或修改调班信息")
    @Transactional
    public R saveAndUpdateShiftInfo(@RequestBody @Valid ShiftVo shiftVo, HttpServletRequest request) throws Exception {
        JSONObject data = loginController.getUserInfo(request).getData();//只能查询自己的信息
        if (ObjectUtils.isEmpty(data)){
            return R.error("请先登录");
        }
        Long id=data.getLong("id");
        ShiftEntity shiftEntity = BeanUtilsMabach.doToDto(shiftVo,ShiftEntity.class);
        UserEntity applyEmp=userService.getByIdE(id);
        shiftEntity.setApplyName(applyEmp.getName());
        shiftEntity.setApplyCode(applyEmp.getUsercode());
        shiftEntity.setApplyOrgId(applyEmp.getOrgId());
        shiftEntity.setApplyUnitId(applyEmp.getDepId());
        shiftEntity.setApplyJobId(applyEmp.getJobId());
        shiftEntity.setApplyOrgName(jobController.getOrgNameById(applyEmp.getOrgId()));
        shiftEntity.setApplyUnitName(jobController.getOrgNameById(applyEmp.getDepId()));
        shiftEntity.setApplyJobName(jobController.getJobName(applyEmp.getJobId()));
        EmployeeInfoEntity shiftEmp=employeeInfoService.getByIdE(shiftVo.getShiftOid());
        shiftEntity.setShiftName(shiftEmp.getName());
        shiftEntity.setShiftCode(shiftEmp.getCode());
        shiftEntity.setShiftOrgId(shiftEmp.getOrgId());
        shiftEntity.setShiftUnitId(shiftEmp.getUnitId());
        shiftEntity.setShiftJobId(shiftEmp.getJobId());
        shiftEntity.setShiftOrgName(jobController.getOrgNameById(shiftEmp.getOrgId()));
        shiftEntity.setShiftUnitName(jobController.getOrgNameById(shiftEmp.getUnitId()));
        shiftEntity.setShiftJobName(jobController.getJobName(shiftEmp.getJobId()));
        EmployeeInfoEntity beShiftEmp=employeeInfoService.getByIdE(shiftVo.getBeShiftOid());
        shiftEntity.setBeShiftName(beShiftEmp.getName());
        shiftEntity.setBeShiftCode(beShiftEmp.getCode());
        shiftEntity.setBeShiftOrgId(beShiftEmp.getOrgId());
        shiftEntity.setBeShiftUnitId(beShiftEmp.getUnitId());
        shiftEntity.setBeShiftJobId(beShiftEmp.getJobId());
        shiftEntity.setBeShiftOrgName(jobController.getOrgNameById(beShiftEmp.getOrgId()));
        shiftEntity.setBeShiftUnitName(jobController.getOrgNameById(beShiftEmp.getUnitId()));
        shiftEntity.setBeShiftJobName(jobController.getJobName(beShiftEmp.getJobId()));
        ArrayList<String> fileUrlList=shiftVo.getFileUrlList();
        if(!CollectionUtils.isEmpty(fileUrlList)) {
            saveFile(shiftEntity.getShiftOid(), fileUrlList, "调班申请附件",24);
        }
        shiftEntity.setFileUrl(CollectionUtils.isEmpty(fileUrlList)?"":ListToString(fileUrlList));
        shiftEntity.setBeShiftDate(shiftVo.getShiftDate());
        if (shiftVo.getId()==null){
            shiftEntity.setCreateTime(new Date());
            shiftService.saveE(shiftEntity);
        }else{
            shiftService.updateByIdE(shiftEntity);
        }
        return R.ok();
    }


    @DeleteMapping("/deleteShift")
    @ApiOperation("删除调班信息")
    @Transactional
    public R deleteShift(@RequestParam(value = "id",required = true) String id){
        shiftDao.deleteById(Long.parseLong(id));
        return R.ok();
    }



    //附件保存
    public void saveFile(Long oid, ArrayList<String> fileList, String name, Integer type){
        for (String s : fileList) {
            imgUrlDao.delete(new QueryWrapper<ImgUrlEntity>().eq("url", s).eq("type", type));
            ImgUrlEntity imgUrlEntity = new ImgUrlEntity();
            imgUrlEntity.setName(name);
            imgUrlEntity.setOid(oid);
            imgUrlEntity.setType(type);
            imgUrlEntity.setCreateTime(new Date());
            imgUrlEntity.setUrl(s);
            imgUrlService.saveE(imgUrlEntity);
        }

    }
    public String ListToString(ArrayList<String> fileUrlList){
        String Url="";
        for ( String s:fileUrlList){
            Url+=s+",";
        }
        return Url.substring(0,Url.length()-1);
    }


}
